//
//  GameOrderNoPayVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/9/6.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class GameOrderNoPayVC: BaseViewController {
    
    var page = -999
    
    var hasmore = "-999"
    
    var dataModels : [GameOrderModel]?
    
    var payment_list : [PaymentListModel]?


    override func viewDidLoad() {
        super.viewDidLoad()

        groupTableView.register(UINib(nibName: StringFromClass(classType: GameOrderCell.self), bundle: nil), forCellReuseIdentifier: GameOrderCell.identifer())
        
        groupTableView.contentInset = UIEdgeInsetsMake(ZMNavMaxY + ZMTitlesViewH, 0, 0, 0)
        
        groupTableView.separatorStyle = .none
        
        
        weak var weakSelf = self
        
        groupTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        groupTableView.mj_header.beginRefreshing()
        
        groupTableView.mj_footer = ZMRefreshFooter.init{
            
            
            weakSelf!.loadMoreData()
            
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    



}




extension  GameOrderNoPayVC{
    
    
    func loadData() {
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        parmeter["state_type"] = "0" as AnyObject
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_order&a=game_order_list", parameters: parmeter) {  [weak self] (responseObject, error) in
            
            
            if error == nil{
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.dataModels = [GameOrderModel]()
                
                
                self?.payment_list = [PaymentListModel]()
                
                for dic in responseObject!["payment_list"] as! [[String : AnyObject]]{
                    
                    self!.payment_list!.append(PaymentListModel(dic: dic))
                    
                }

                
                
                for dic in responseObject!["datas"]!["order_list"] as! [[String : AnyObject]]{
                    
                    let temp = dic["extend_order_goods"]?[0] as? [String : AnyObject]
                    
                    let paySn = dic["pay_sn"]
                    
                    
                    if temp != nil{
                        
                        let model = GameOrderModel(dic: temp!)
                        
                        model.pay_sn = paySn as? String
                        
                        model.state_desc = "去支付"
                        
                        self!.dataModels!.append(model)
                        
                    }
                    
                    
                    
                }
                
                
                
                
                self!.groupTableView.mj_footer.resetNoMoreData()
                
                
                if self?.hasmore == "0" {
                    
                    self!.groupTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }
                
                
                if self!.dataModels!.count == 0{
                    
                    
                    self?.showLogoView(text : "暂无相关订单...")
                    
                    
                }
                
                
                self!.groupTableView.mj_header.endRefreshing()
                
                self!.groupTableView.reloadData()
                
                
                
                
                
            }else{
                
                
                
                self!.groupTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
            }
            
            
        }
        
        
        
    }
    
    func loadMoreData() {
        
        page += 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        parmeter["state_type"] = "0" as AnyObject
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_order&a=game_order_list", parameters: parmeter) {  [weak self] (responseObject, error) in
            
            
            if error == nil{
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                for dic in responseObject!["datas"]!["order_list"] as! [[String : AnyObject]]{
                    
                    let temp = dic["extend_order_goods"]?[0] as? [String : AnyObject]
                    
                    let paySn = dic["pay_sn"]
                    
                    
                    if temp != nil{
                        
                        let model = GameOrderModel(dic: temp!)
                        
                        model.pay_sn = paySn as? String
                        
                        model.state_desc = "去支付"
                        
                        self!.dataModels!.append(model)
                        
                    }
                    
                    
                    
                }
                
                
                
                if self?.hasmore == "0" {
                    
                    self!.groupTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }else{
                    
                    self!.groupTableView.mj_footer.endRefreshing()
                    
                }
                
                
                
                
                self!.groupTableView.reloadData()
                
                
                
                
            }else{
                
                
                
                self!.groupTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
        }
        
        
    }
    
    
}




// MARK:- tableview代理方法
extension GameOrderNoPayVC{
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        return dataModels!.count
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        return 1
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let tableCell : GameOrderCell =  tableView.dequeueReusableCell(withIdentifier: GameOrderCell.identifer()) as! GameOrderCell
        
        tableCell.model = dataModels?[indexPath.section]
        
        tableCell.delegate = self
        
        
        return tableCell
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 150
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return 0.00001
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            
            return 0.00001
            
        } else {
            
            return 8
            
        }
        
    }
    
    
    
    
    
}


extension GameOrderNoPayVC : GameOrderCellDelegate{
    
    
    func payBtnDidTap(model : GameOrderModel){
    
    
        if payment_list == nil {
            return
        }
        
        let paySnStr = model.pay_sn
        
        if paySnStr == nil {
            return
        }
        
        let tempVC = UIAlertController(title: nil, message: "选择支付方式", preferredStyle: .actionSheet)
        
        let ation1 = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        tempVC.addAction(ation1)
        
        for item in payment_list! {
            
            if item.payment_code == "alipay_app" {
                
                let ation2 = UIAlertAction(title: item.payment_name, style: .default, handler: { (_) in
                    
                    self.startPay(payment: "alipay_app", paySn: paySnStr!)
                    
                })
                
                tempVC.addAction(ation2)
                
                
            } else if item.payment_code == "wxpay_app"{
                
                let ation3 = UIAlertAction(title: item.payment_name, style: .default, handler: { (_) in
                    
                    self.startPay(payment: "wxpay_app", paySn: paySnStr!)
                    
                })
                
                tempVC.addAction(ation3)
                
                
            }else{
                
                let ation4 = UIAlertAction(title: item.payment_name, style: .default, handler: { (_) in
                    
                    self.startPay(payment: "99bill_app", paySn: paySnStr!)
                    
                })
                
                tempVC.addAction(ation4)
                
                
                
            }
            
        }
        
        
        
        
        
        present(tempVC, animated: true, completion: nil)
    
    }
    
    
    
    
    
    
    func startPay(payment : String,paySn : String) {
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["payment_code"] = payment as AnyObject
        parmeter["pay_sn"] = paySn as AnyObject
        
        NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_buy&a=game_pay_from_list", parameters: parmeter) {  [weak self] (responseObject, error) in
            
            if error == nil{
                
                if payment == "alipay_app"{
                    
                    let aliPayStr = responseObject?["datas"]?["orderString"]
                    
                    QL1(aliPayStr)
                    
                    if aliPayStr != nil{
                        
                        self?.AliPay(payStr: aliPayStr! as! String)
                        
                    }
                    
                    
                    
                }else if payment == "wxpay_app"{
                    
                    let WXPayDic = responseObject?["datas"]?["wxpay_param"]
                    
                    if WXPayDic != nil{
                        
                        QL1(WXPayDic)
                        
                        self?.WXPay(dic: WXPayDic! as! [String : AnyObject])
                        
                        
                    }
                    
                    
                }else{
                    
                    
                    let KQPayStr = responseObject?["datas"]?["orderString"]
                    
                    QL1(KQPayStr)
                    
                    
                    if KQPayStr != nil{
                        
                        self?.KQPay(payStr: KQPayStr! as! String)
                        
                    }
                    
                    
                }
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
            
            
        }
        
        
        
        
    }
    
    
    
    
    
    
    
    func AliPay(payStr : String){
        
        
        AlipaySDK.defaultService().payOrder(payStr, fromScheme: "com.xiaojing.mall") { (_) in
            
        }
        
        
        
    }
    
    
    func WXPay(dic : [String : AnyObject]) {
        
        let temp  = PayReq()
        
        //由用户微信号和AppID组成的唯一标识，用于校验微信用户
        temp.openID = dic["appid"] as! String
        
        // 商家id，在注册的时候给的
        temp.partnerId = dic["partnerid"] as! String
        
        // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
        temp.prepayId  = dic["prepayid"] as! String
        
        // 根据财付通文档填写的数据和签名
        //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
        temp.package   = dic["pkg"] as! String
        
        // 随机编码，为了防止重复的，在后台生成
        temp.nonceStr  = dic["noncestr"] as! String
        
        // 这个是时间戳，也是在后台生成的，为了验证支付的
        let str = dic["timestamp"] as! String
        
        let temUin = UInt32(str)
        
        if temUin != nil {
            
            temp.timeStamp = temUin!
            
        }
        
        
        // 这个签名也是后台做的
        temp.sign = dic["sign"] as! String
        
        //发送请求到微信，等待微信返回onResp
        
        WXApi.send(temp)
        
        
        
    }
    
    
    func KQPay(payStr : String) {
        
        let temp = GoodsDetailController()
        
        temp.urlStr = payStr
        
//        QL1(temp.urlStr)
        
        temp.navigationItem.title = "快钱收银台"
        
        temp.hiddenBar = false
        
        
        navigationController?.pushViewController(temp, animated: true)
        
        
        
    }
    
    


}

